#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Time    : 2019/11/1 9:53
# Author  : simple0426
# Email   : istyle.simple@gmail.com
# File    : rabbitmq_pika_consumer.py
# Software: PyCharm
import pika, sys

# 建立链接
auth = pika.credentials.PlainCredentials('ever01', 'Theistyle')
# 连接单个mq实例
# conn_para = pika.ConnectionParameters(
#     host='127.0.0.1',
#     port=5672,
#     virtual_host='celery',
#     credentials=auth
# )

# 连接多个mq实例
conn_para = (
    pika.ConnectionParameters(
        host='192.168.31.231',
        port=5672,
        virtual_host='celery',
        credentials=auth,
        connection_attempts=3,
        retry_delay=1
    ),
    pika.ConnectionParameters(
        host='192.168.31.232',
        port=5672,
        virtual_host='celery',
        credentials=auth,
        connection_attempts=3,
        retry_delay=1
    ),
    pika.ConnectionParameters(
        host='192.168.31.233',
        port=5672,
        virtual_host='celery',
        credentials=auth,
        connection_attempts=3,
        retry_delay=1
    ),
)
conn = pika.BlockingConnection(parameters=conn_para)

# 创建channel
channel = conn.channel()
channel.queue_declare(queue='hello', durable=True) # 创建queue
# direct模式
# channel.exchange_declare( # 创建exchange
#     exchange='direct_log',
#     exchange_type='direct',
#     durable=True)
# topic模式
# channel.exchange_declare( # 创建exchange
#     exchange='topic_log',
#     exchange_type='topic',
#     durable=True)
channel.exchange_declare( # 创建exchange
    exchange='fanout_log',
    exchange_type='fanout',
    durable=True)

# 定义接收的key，并将queue和exchange绑定【建立通道接收消息】
# key = sys.argv[1] # 命令行接收routing_key
# if not key:
#     sys.stderr.write("Usage:%s key \n" % sys.argv[0])
#     sys.exit(1)
channel.queue_bind(
    # exchange='direct_log',
    # exchange='topic_log',
    exchange='fanout_log',
    queue='hello',
    # routing_key=key # fanout模式下无需绑定绑定key
)

# 消费消息
def callback(ch, method, properties, body): # 消息的具体功能
    print("[x] Received %r:%r" % (method.routing_key, body))

channel.basic_consume(
    queue='hello',
    on_message_callback=callback,
    auto_ack=True
)
print('[*] Waiting for logs.To exit press CTRL+C')
channel.start_consuming() # 开启阻塞式消费，持续接收发布的消息
